#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import os
import subprocess
import platform
import argparse

TAR_TEMPLATE = "ggintemp.tar.gz"

BLACK_LIST = {
    "ggintemp-cli.py": True,
    "ggintemp-cli.sh": True,
}

PLATFORM = platform.system()

SUPPORT_MODULE = ["redis", "mysql", "casbin", "validate", "cron", "oss"]

SUPPORT_MODULE_STR = " ".join(SUPPORT_MODULE)

def args_parse():
    args = argparse.ArgumentParser(description = 'genarate a new project', epilog = 'CopyRight@ skybosi', formatter_class=argparse.RawTextHelpFormatter)
    args.add_argument("-p",'--project', type = str, required=True, help = "Set a project name")
    args.add_argument("-m","--module",  type = str, required=False, help = "Add module into this project\nmodule option: \n  " + SUPPORT_MODULE_STR, default = "None", nargs = '*')
    args = args.parse_args()
    return args

def run_shell(args):
    print(args)
    if isinstance(args, list):
        cmd = " ".join(args)
    elif isinstance(args, str) and len(args) != 0:
        cmd = args
    else:
        exit
    res = subprocess.getstatusoutput(cmd)
    status = res[0]
    if status != 0:
        print(cmd, res)
        raise ValueError("execute " + cmd + " error!")
    else:
        return res

def init():
    run_shell(["export GO111MODULE=on", "&&", "export GOPROXY=https://goproxy.cn/"])

# 解压模板文件
def untar(template):
    res = run_shell(["tar", "-xvf", template])
    status = res[0]
    if status != 0:
        print("unzip " + template + " error")

# 从模板目录生成project目录
def getproject(project):
    os.rename("template", project)

# 替换代码中的{{template}} {{Template}}
def replace_template(project):
    # 替换代码中的 {{template}}
    res = run_shell(["grep", "-rl", "{{template}}", project])
    status = res[0]
    if status == 0:
        result = res[1]
        files = result.splitlines()
        for file in files:
            if not BLACK_LIST.get(os.path.basename(file)):
                if "Darwin" == PLATFORM:
                    res = run_shell(["sed", "-i", '"" "s/{{template}}/'+ project + '/g"', file])
                elif "Windows" != PLATFORM:
                    res = run_shell(["sed", "-i", '"s/{{template}}/'+ project + '/g"', file])
                else:
                    print("invalid platform!")
    else:
        exit
    # 替换代码中的 {{Template}}
    Pproject = project.capitalize()
    res = run_shell(["grep", "-rl", "{{Template}}", project])
    status = res[0]
    if status == 0:
        result = res[1]
        files = result.splitlines()
        for file in files:
            if not BLACK_LIST.get(os.path.basename(file)):
                if "Darwin" == PLATFORM:
                    res = run_shell(["sed", "-i", '"" "s/{{Template}}/'+ Pproject + '/g"', file])
                elif "Windows" != PLATFORM:
                    res = run_shell(["sed", "-i", '"s/{{Template}}/'+ Pproject + '/g"', file])
                else:
                    print("invalid platform!")
    else:
        exit

# 重命名project中的template的文件
def rename_template(project, dir = None):
    root = os.path.abspath(dir or project)
    files = os.listdir(dir or project)
    # print(root, dir)
    for i, f in enumerate(files):
        file = os.path.join(root, f)
        if os.path.isfile(file):
            basename, ext = os.path.splitext(f)
            if basename == "template":
                OldName = file
                NewName = os.path.join(root, project + ext)
                # print(i, OldName, project, NewName)
                os.rename(OldName, NewName)
        elif os.path.isdir(file):
            rename_template(project, file)

# 添加需要的module
def add_module(modules, project):
    modules_mp = {}
    for m in modules:
        modules_mp[m] = 1
    for m in SUPPORT_MODULE:
        res = run_shell(["grep", "-rl", "{{" + m + "}}", project])
        status = res[0]
        if status == 0:
            result = res[1]
            files = result.splitlines()
            for file in files:
                if "Darwin" == PLATFORM:
                    if 1 == modules_mp.get(m): # 去除注释
                        res = run_shell(["sed", "-i", '"" "s/{{' + m + '}}//g"', file])
                    else:                  # 替换为注释
                        res = run_shell(["sed", "-i", '"" "s/{{' + m + '}}/\/\//g"', file])
                elif "Windows" != PLATFORM:
                    if 1 == modules_mp.get(m): # 去除注释
                        res = run_shell(["sed", "-i", '"s/{{' + m + '}}//g"', file])
                    else:                  # 替换为注释
                        res = run_shell(["sed", "-i", '"s/{{' + m + '}}/\/\//g"', file])
                else:
                    print("invalid platform!")
        else:
            exit    

# 通过Makefile编译
def build_project(project):
    res = run_shell(["cd " + project, "&&", 'make build'])

if __name__=="__main__":
    options = args_parse()
    if os.path.exists(options.project):
        print("project " + options.project + " is exist")
    else:
        init()
        untar(TAR_TEMPLATE)
        getproject(options.project)
        replace_template(options.project)
        rename_template(options.project)
        add_module(options.module, options.project)
        build_project(options.project)
